#include <stdio.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <string.h>
#include <unistd.h>


int fd;
int len;
int ret;
char gpio_path[100];

int gpio_export(char *argv){
    fd = open("/sys/class/gpio/export",O_WRONLY);
    if(fd < 0)
    {
        printf("open /sys/class/gpio/export error\n");
        return -1;
    }
    len = strlen(argv);
    ret = write(fd,argv,len);
    if(ret < 0)
    {
        printf("open /sys/class/gpio/export error\n");
        close(fd);
        return -2;
    }
    close(fd);
}

int gpio_unexport(char *argv){
    fd = open("/sys/class/gpio/unexport",O_WRONLY);
    if(fd < 0)
    {
        printf("open /sys/class/gpio/unexport error\n");
        return -1;
    }
    len = strlen(argv);
    ret = write(fd,argv,len);
    if(ret < 0)
    {
        printf("open /sys/class/gpio/unexport error\n");
        close(fd);
        return -2;
    }
    close(fd);
}

int gpio_ctrl(char *arg,char *val){
    char file_path[100];
    sprintf(file_path, "%s/%s", gpio_path,arg);

    fd = open(file_path,O_WRONLY);
    if(fd < 0)
    {
        printf("open file_path error\n");
        return -1;
    }
    len = strlen(val);
    ret = write(fd,val,len);
    if(ret < 0)
    {
        printf("open file_path error\n");
        close(fd);
        return -2;
    }
    close(fd);
}

int main(int argc, char *argv[])
{
    sprintf(gpio_path, "/sys/class/gpio/gpio%s", argv[1]);
    if(access(gpio_path,F_OK))
    {
        gpio_export(argv[1]);
    }
    else
    {
        gpio_unexport(argv[1]);
    }
    gpio_ctrl("direction", "out");
    gpio_ctrl("value", argv[2]);
    gpio_unexport(argv[1]);
}
